clear all
set more off
set mem 100m
tempfile temp

local data ../../../../../data/elections/2006/round1
local working ../working

** 2007-2011
local files : dir "`data'" files "*.txt"
di `files'

local r = 1
foreach file in `files' {
	import delimited using `data'/`file', clear
	gen ubigeo = "`file'"
	cap keep if regexm(v2,"Votos")
	cap destring v3, ignore(",") replace
	cap gen voted = v3 if v2 == "Total de Votos VÃ¡lidos"
	cap gen voted_blank = v3 if v2  == "Votos Blancos"
	cap gen voted_null = v3 if v2   == "Votos Nulos"
	
	cap gen voted = 0
	
	replace ubigeo = substr(ubigeo,1,6)
	collapse (sum) voted*, by(ubigeo)
	
	save `data'/r`r', replace
	
	local ++r
}

local r = `r' - 1

use `data'/r1, clear
forvalues x = 2/`r' {
	append using `data'/r`x'
}	

gen dep = real(substr(ubigeo,1,2))
keep if dep <= 25

replace dep = dep + 1 if dep > 6

recode dep (25 = 7) (26 = 25)

gen ubigeonac1993 = ubigeo
collapse (sum) vote*, by(ubigeonac1993)

gen totalvotos = voted + voted_blank + voted_null

replace voted = voted / totalvotos
replace voted_null = voted_null / totalvotos
replace voted_blank = voted_blank / totalvotos

gen lv = ln(totalvotos)

save `working'/vote_onpe_dist, replace

forvalues x = 1/`r' {
	erase `data'/r`x'.dta
}	
	
